//
//  ImagePreviewViewController.m
//  OntheRoadV4
//
//  Created by ZhangYanhua on 15/5/17.
//  Copyright (c) 2015年 EricHuang. All rights reserved.
//

#import "ImagePreviewViewController.h"
#import "ALAssetsLibrary+CustomPhotoAlbum.h"
#import "PHPhotoLibrary+CustomPhotoAlbum.h"
#import "MBProgressHUD.h"
#import "QWImageMangerConfig.h"

@interface ImagePreviewViewController ()

@property (nonatomic, strong) UIImage *bigImage;
@property (nonatomic, strong) NSDictionary *metaData;

@end

@implementation ImagePreviewViewController

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:[QWImageMangerConfig baseBundle]];
    if (self)
    {
        
    }
    return self;
}

- (id)initWithImage:(UIImage *)image metaData:(NSDictionary *)metaData
{
    self = [super init];
    if (self) {
        _bigImage = image;
        _metaData = metaData;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [self.retakeBtn setTitle:QWImagePickerLocalizedString(@"Retake", nil) forState:UIControlStateNormal];
    [self.saveBtn setTitle:QWImagePickerLocalizedString(@"Save", nil) forState:UIControlStateNormal];
    
    self.imageView.image = _bigImage;
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

-(void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self.navigationController setNavigationBarHidden:YES];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)confirmBtnPressed:(id)sender
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.customView = [MBProgressHUD getCustomSpinner];
        hud.mode = MBProgressHUDModeCustomView;
        hud.labelText = QWImagePickerLocalizedString(@"EditRecordSaving...", nil);
    });


    if(NSClassFromString(@"PHPhotoLibrary"))
    {
        PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
        //ALAssetsLibrary *library = [QWImageMangerConfig sharedAssetsLibrary];
        [library saveImage:self.bigImage
                   toAlbum:nil
              withMetaData:self.metaData
       withCompletionBlock:^(NSString *assetURL, NSError *error) {
           if (!assetURL) {
               [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
               [QWImageMangerConfig requestErorrMBProgressHUDDisplay:self.view
                                                     msg:QWImagePickerLocalizedString(@"Save failed!", nil)];
           } else {
               [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
               
               [QWImageMangerConfig requestSuccessMBProgressHUDDisplay:self.view
                                                       msg:QWImagePickerLocalizedString(@"Saved", nil)];
               

               PHFetchResult  *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetURL] options:nil];
               
               if ([result count])
               {
                   PHAsset  *asset = [result objectAtIndex:0];
                   if ([self.delegate respondsToSelector:@selector(DidSaveImageWithInfo:)]) {
                       NSMutableDictionary * infoDic = [NSMutableDictionary dictionary];
                       if (asset)
                       {
                           [infoDic setValue:asset forKey:@"asset"];
                       }
                       [self.delegate DidSaveImageWithInfo:infoDic];
                   }

               }else
               {
                   //DebugLog(@"PHPhotoLibrary save fail");
               }
               /*
               [library assetForURL:assetURL
                        resultBlock:^(ALAsset *asset) {
                            if ([self.delegate respondsToSelector:@selector(DidSelectOneFilter:)]) {
                                NSMutableDictionary * infoDic = [NSMutableDictionary dictionary];
                                
                                [infoDic setValueIfNotNil:asset forKey:@"asset"];
                                
                                [self.delegate DidSaveImageWithInfo:infoDic];
                            }
                            
                        } failureBlock:^(NSError *error) {
                        }];*/
           }
       }];
    }else
    {
        ALAssetsLibrary *library = [QWImageMangerConfig sharedAssetsLibrary];
        [library saveImage:self.bigImage
                   toAlbum:nil
              withMetaData:self.metaData
       withCompletionBlock:^(NSURL *assetURL, NSError *error) {
           if (!assetURL) {
               [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
               [QWImageMangerConfig requestErorrMBProgressHUDDisplay:self.view
                                                     msg:QWImagePickerLocalizedString(@"Save failed!", nil)];
           } else {
               [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
               
               [QWImageMangerConfig requestSuccessMBProgressHUDDisplay:self.view
                                                       msg:QWImagePickerLocalizedString(@"Saved", nil)];
               
               [library assetForURL:assetURL
                        resultBlock:^(ALAsset *asset) {
                            if ([self.delegate respondsToSelector:@selector(DidSaveImageWithInfo:)]) {
                                NSMutableDictionary * infoDic = [NSMutableDictionary dictionary];
                                if (asset){
                                    [infoDic setValue:asset forKey:@"asset"];
                                }
                                [self.delegate DidSaveImageWithInfo:infoDic];
                            }
                            
                        } failureBlock:^(NSError *error) {
                        }];
           }
       }];
    }

}

- (IBAction)retakeBtnPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
